//
//  DoMainVC.m
//  stone-story
//
//  Created by liu dodo on 12-9-24.
//  Copyright (c) 2012年 liu dodo. All rights reserved.
//

#import "DoMainVC.h"

@interface DoMainVC ()

@end

@implementation DoMainVC
@synthesize queue;
@synthesize resultArray=_resultArray;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
     [self.view setBackgroundColor:[UIColor grayColor]];
    
    
    //店面按钮
    UIButton *shopBtn = [[UIButton alloc]init];
    [shopBtn setFrame:CGRectMake(0,0,203,138)];
    [shopBtn setBackgroundImage:[UIImage imageNamed:@"btn_shop.jpg"] forState:UIControlStateNormal];
    [shopBtn addTarget:self action:@selector(onShopBtn_Click) forControlEvents:UIControlEventTouchUpInside];
    [shopBtn.titleLabel setTextColor:[UIColor whiteColor]];
    [shopBtn.titleLabel setFont:[UIFont fontWithName:@"Thonbur-bold" size:13.0]];
    [shopBtn setBackgroundColor:[UIColor clearColor]];
    
    [self.view addSubview:shopBtn];
    
    //产品按钮
    UIButton *productBtn = [[UIButton alloc]init];
    [productBtn setFrame:CGRectMake(shopBtn.frame.origin.x,shopBtn.frame.size.height,203,120)];
    [productBtn setBackgroundImage:[UIImage imageNamed:@"btn_product.jpg"] forState:UIControlStateNormal];
    [productBtn addTarget:self action:@selector(onproductBtn_Click) forControlEvents:UIControlEventTouchUpInside];
    [productBtn.titleLabel setTextColor:[UIColor whiteColor]];
    [productBtn.titleLabel setFont:[UIFont fontWithName:@"Thonbur-bold" size:13.0]];
    [productBtn setBackgroundColor:[UIColor clearColor]];
    
    [self.view addSubview:productBtn];
    
    
    //公司按钮
    UIButton *companyBtn = [[UIButton alloc]init];
    [companyBtn setFrame:CGRectMake(productBtn.frame.origin.x,productBtn.frame.origin.y+productBtn.frame.size.height,203,122)];
    [companyBtn setBackgroundImage:[UIImage imageNamed:@"btn_company.jpg"] forState:UIControlStateNormal];
    [companyBtn addTarget:self action:@selector(onCompanyBtn_Click) forControlEvents:UIControlEventTouchUpInside];
    [companyBtn.titleLabel setTextColor:[UIColor whiteColor]];
    [companyBtn.titleLabel setFont:[UIFont fontWithName:@"Thonbur-bold" size:13.0]];
    [companyBtn setBackgroundColor:[UIColor clearColor]];
    
    [self.view addSubview:companyBtn];
    
    //底部图片
    UIImageView *bottomImg=[[UIImageView alloc] initWithFrame:CGRectMake(companyBtn.frame.origin.x, companyBtn.frame.size.height+companyBtn.frame.origin.y, companyBtn.frame.size.width, 324)];
    [bottomImg setBackgroundColor:[UIColor clearColor]];
    [bottomImg setImage:[UIImage imageNamed:@"btn_button.jpg"]];
    [self.view addSubview:bottomImg];
    
    //主页图片
    UIImageView *mainImg=[[UIImageView alloc] initWithFrame:CGRectMake(shopBtn.frame.size.width, 0, 821,704)];
    [mainImg setBackgroundColor:[UIColor clearColor]];
    [mainImg setImage:[UIImage imageNamed:@"mainBG.png"]];
    [self.view addSubview:mainImg];
    
    
    
    //主页广告BNNAR
    XLCycleScrollView *csView = [[XLCycleScrollView alloc] initWithFrame:CGRectMake(214, 12, 769, 380)];
    [csView setBackgroundColor:[UIColor clearColor]];
   
    csView.delegate = self;
    csView.datasource = self;
    [self.view addSubview:csView];
    
  
    csView.layer.shadowOffset = CGSizeMake(5, 3);
    csView.layer.shadowOpacity = 0.6;
    csView.layer.shadowColor = [UIColor blackColor].CGColor;
 
    // 开发在其他地方用这里的方法判断是否第一次
   if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {
        
        
       /* 
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"第一次"
                                                      message:@"进入App"
                                                     delegate:self
                                            cancelButtonTitle:@"我知道了"
                                            otherButtonTitles:nil];
        [alert show];
        */
       [self LoadXmlTest];
        
        
    }
   
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
   return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||interfaceOrientation==UIInterfaceOrientationLandscapeRight  );
    //return NO;
}

#pragma 按钮触发事件
//店面按钮触发事件
-(void)onShopBtn_Click
{
    ShopListVC *tcvc=[[ShopListVC alloc]init];

    [self.navigationController pushViewController:tcvc animated:YES];//视图推出
}
//公司信息按钮触发事件
-(void)onCompanyBtn_Click
{
    CompanyInfoVC *companyinfoVC=[[CompanyInfoVC alloc]init];
    // tcvc.navigationItem.title=[NSString stringWithFormat:@"%@",@"测试"];//设置导航标题
    // [tcvc.view setBackgroundColor:[UIColor redColor]];
    [self.navigationController pushViewController:companyinfoVC animated:YES];//视图推出
}
//产品按钮触发事件
-(void)onproductBtn_Click
{
    popTableVC=[[PopoverTableVC alloc] initWithStyle:UITableViewStylePlain];
    popTableVC.delegate=self;
   
    //首先弹出的是 父类ID为0的VC
    popTableVC.parentcategroyID=@"0";
     
     UINavigationController *navController =[[UINavigationController alloc] initWithRootViewController: popTableVC];
    

    
    popover = [[UIPopoverController alloc] initWithContentViewController:navController];
    [popover setDelegate:self];
    [popover setPopoverContentSize:CGSizeMake(250,400)];
    popTableVC.contentSizeForViewInPopover=popTableVC.view.bounds.size;
    [popover presentPopoverFromRect:CGRectMake(0,138,203,138) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];
}
- (void)popoverControllerDidDismissPopover:(UIPopoverController*)popoverController{
    if (popover) {
        [popover dismissPopoverAnimated:YES];
        // [popover release];
        popover=nil;
        if (popTableVC != nil) {
            // [popoverContent release];
            popTableVC = nil;
        }
    }
}
-(void)killPopoversOnSight {
    if (popover) {
        [popover dismissPopoverAnimated:NO];
    }
}

#pragma 实现PopoverTableVCDelegate 代理方法

- (void)PopoverTableVCDoneAction:(NSString *)name 
{
    [popover dismissPopoverAnimated:NO];
  
   /* UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:[NSString stringWithFormat:@"你选择的ID是什么:%@",name]
                                                   delegate:self
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
    */
    LCProudctListVC *prodListVC=[[LCProudctListVC alloc]init];
    prodListVC.product_type=name;
    // tcvc.navigationItem.title=[NSString stringWithFormat:@"%@",@"测试"];//设置导航标题
    // [tcvc.view setBackgroundColor:[UIColor redColor]];
    [self.navigationController pushViewController:prodListVC animated:YES];//视图推出
}


#pragma CycleSrollView 轮转图片代理
- (NSInteger)numberOfPages
{
    return 5;
}

- (UIView *)pageAtIndex:(NSInteger)index
{
  
    UIImageView *page=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 769, 380)];
    page.backgroundColor=[UIColor clearColor];
    //[page setImageWithURL:[NSURL URLWithString:[cell_text objectForKey:@"pic"]] placeholderImage:[UIImage imageNamed:@"picHolder.png"]];
    [page setImage:[UIImage imageNamed:[NSString stringWithFormat:@"main%d.jpg",index]]];
    
    CALayer *l = [page layer];   //获取ImageView的层
    [l setMasksToBounds:YES];
    [l setCornerRadius:8.0];
  
    
    return page;
}

- (void)didClickPage:(XLCycleScrollView *)csView atIndex:(NSInteger)index
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:[NSString stringWithFormat:@"当前点击第%d个页面",index]
                                                   delegate:self
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
  
}










//测试加载XML
-(void)LoadXmlTest
{
    _resultArray = [[NSMutableArray alloc] init];
    
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    
    [self.view addSubview:HUD];
    HUD.delegate = self;
    // HUD.labelText = @"Loading...";
    HUD.mode=MBProgressHUDModeIndeterminate;
    [HUD show:YES];
    
    //传健请求队列
    if (![self queue]) {
        
        [self setQueue:[[NSOperationQueue alloc] init]];
    }
    NSURL *url = [NSURL URLWithString:ProductCategroyAPI];
    
    ASIHTTPRequest *request2 = [ASIHTTPRequest requestWithURL:url];
    [request2 setDelegate:self];
    [request2 setDidFinishSelector:@selector(requestDone:)];
    [request2 setDidFailSelector:@selector(requestWentWrong:)];
    [[self queue] addOperation:request2];
    
}



//when the request is done
//如果请求成功的时候调用的函数
-(void)requestDone:(ASIHTTPRequest *)request
{
    
    //NSLog(@"%@",[request responseString]);
    NSData *XMLData =[request responseData];
    
    //生成CXMLDocument对象：
    CXMLDocument *document = [[CXMLDocument alloc] initWithData:XMLData options:0 error:nil];
    //使用parseDire来解析(推荐):
    [self parseDire:document];
    [HUD hide:YES afterDelay:0];
    
}
//when the rquest ment error
//当请求遇见错误的时候调用的函数
- (void)requestWentWrong:(ASIHTTPRequest *)request
{
    [HUD hide:YES];
    NSError *error = [request error];
    NSLog(@"%@",error);
    
  	MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
	
	// Configure for text only and offset down
	hud.mode = MBProgressHUDModeText;
	hud.labelText = NSLocalizedString(@"连接超时,请检查网络...",@"");
	hud.margin = 10.f;
	hud.yOffset = 120.f;
	hud.removeFromSuperViewOnHide = YES;
	[hud hide:YES afterDelay:3];
    
    
}

#pragma mark --解析函数
- (void)parseDire:(CXMLDocument *) document
{
    NSLog(@"dodo 开始使用parseDire解析." );
    NSArray *items = NULL;
    //注意，这是用XML PATH来取得元素集:
    items = [document nodesForXPath:@"//Category" error:nil];
    //NSLog(@"dodo parseDire解析- 元素数: %d", items.count) ;
    for (CXMLElement *element in items)
    {
        if ([element isKindOfClass:[CXMLElement class]])
        {
            NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
            for (int i = 0; i < [element childCount]; i++)
            {
                if ([[[element children] objectAtIndex:i]
                     isKindOfClass:[CXMLElement class]])
                {
                    [item setObject:[[element childAtIndex:i] stringValue]
                             forKey:[[element childAtIndex:i] name]
                     ];
                }
            }
            [_resultArray addObject:item];
            
        }
    }
    
    
    NSLog(@"数组中元素数: %d", _resultArray.count );
    //然后从控制台读取相关内容:
    
    
    [self FMDB_init];
    [self createTable];
    [self deleteRecord];
    
    for (NSMutableDictionary* dict in _resultArray) {
        // NSLog(@"子字典元素数: %d", dict.count);
        /* NSLog(@"类别ID是什么: %@", [dict objectForKey:@"CategoryID"] );
         NSLog(@"类别名称是: %@\n", [dict objectForKey:@"CategoryName"] );
         NSLog(@"类别的父类别是: %@\n", [dict objectForKey:@"ParentCategoryID"] );
         NSLog(@"备注是: %@\n", [dict objectForKey:@"Note"] );*/
        
        if([self isExistTable:@"tb_categroy" InTheDateBase:db]){
            [db executeUpdate:@"INSERT INTO tb_categroy (categroy_id,categroy_name,parentcategory_id,note) VALUES (?,?,?,?)",[dict objectForKey:@"CategoryID"],[dict objectForKey:@"CategoryName"],[dict objectForKey:@"ParentCategoryID"],[dict objectForKey:@"Note"]];
            
        }
        else {
            NSLog(@"table db.Products have not exist!");
        }
        
    }
    
    [self queryTable];
    
}


#pragma mark - 数据库操作
//创建或打开数据库
- (void)FMDB_init//1
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    
    //dbPath： 数据库路径，在Document中。
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"db_stoneStory.db"];
    
    //创建数据库实例 db  这里说明下:如果路径中不存在"Test.db"的文件,sqlite会自动创建"Test.db"
    db= [FMDatabase databaseWithPath:dbPath];
    if (![db open]) {
        NSLog(@"Could not open db.");
        return ;
    }
    else {
        NSLog(@"open db. success!");
    }
    
    
    
}
//创建表
- (void)createTable
{
    //创建一个名为User的表，四个字段 书的ID,书的图片文件名,书的pdf文件名,书的排号
    if(![self isExistTable:@"tb_categroy" InTheDateBase:db])
        [db executeUpdate:@"CREATE TABLE tb_categroy (categroy_id text,categroy_name text,parentcategory_id text,note text)"];
    else {
        NSLog(@"table tb_categroy have exist!");
    }
}

//插入数据
- (void)insertRecord
{
    if([self isExistTable:@"tb_categroy" InTheDateBase:db])
    {
        //[db executeUpdate:@"INSERT INTO Products (product_id,product_image) VALUES (?,?)",[NSNumber numberWithInt:1],@"aaa.jpg"];
        //[db executeUpdate:@"INSERT INTO Products (product_id,product_image) VALUES (?,?)",[NSNumber numberWithInt:2],@"bbb.jpg"];
        //[db executeUpdate:@"INSERT INTO Products (product_id,product_image) VALUES (?,?)",[NSNumber numberWithInt:3],@"ccc.jpg"];
    }
    else
    {
        NSLog(@"table tb_categroy have not exist!");
    }
}

//查询
- (void)queryTable
{
    //返回数据库中第一条满足条件的结果
    //   NSString *aa=[db stringForQuery:@"SELECT Name FROM User WHERE Age = ?",@"20"];
    
    //返回全部查询结果
    FMResultSet *rs=[db executeQuery:@"SELECT * FROM tb_categroy ORDER BY categroy_id ASC"];
    
    //rs=[db executeQuery:@"SELECT * FROM User WHERE Age = ?",@"20"];
    
    while ([rs next])
    {
        NSLog(@"\n categroy_id:%@ \n categro_image:%@ \n  parentcategory_id:%@ \n note:%@ \n ",[rs stringForColumn:@"categroy_id"],[rs stringForColumn:@"categroy_name"],[rs stringForColumn:@"parentcategory_id"],[rs stringForColumn:@"note"]);
    }
    [rs close];
    [db close];
}


//更新数据 将“张三”更改为“李四”
-(void)updateRecord
{
    
    [db executeUpdate:@"UPDATE User SET Name = ? WHERE Name = ? ",@"李四",@"张三"];
    
}


//删除数据
- (void)deleteRecord
{
    if([self isExistTable:@"tb_categroy" InTheDateBase:db])
    {
        [db executeUpdate:@"DELETE FROM tb_categroy "];
    }
    else
    {
        NSLog(@"table tb_categroy have not exist!");
    }
}


//判断是否存在该表
-(BOOL)isExistTable:(NSString*)tablename InTheDateBase:(FMDatabase *)tdb {
    
    FMResultSet *rs = [tdb executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", tablename];
    while ([rs next])
    {
        // just print out what we've got in a number of formats.
        NSInteger count = [rs intForColumn:@"count"];
        NSLog(@"isTableOK %d", count);
        
        if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    
    return NO;
}







@end
